<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web服务监控系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            align-items: center;
        }
        .overview {
            background-color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-around;
        }
        .overview-item {
            text-align: center;
        }
        .overview-number {
            font-size: 24px;
            font-weight: bold;
        }
        .overview-label {
            font-size: 14px;
            color: #666;
        }
        .normal-count {
            color: #28a745;
        }
        .error-count {
            color: #dc3545;
        }
        .filters {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: end;
        }
        .filter-input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .filter-select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .filter-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            height: fit-content;
        }
        .filter-btn:hover {
            background-color: #0056b3;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .status {
            padding: 5px 10px;
            border-radius: 4px;
            color: white;
            font-weight: bold;
            text-align: center;
        }
        .status.normal {
            background-color: #28a745;
        }
        .status.error {
            background-color: #dc3545;
        }
        .status.unknown {
            background-color: #6c757d;
        }
        .refresh-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 2px;
        }
        .refresh-btn:hover {
            background-color: #0056b3;
        }
        .edit-btn {
            background-color: #ffc107;
            color: black;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 2px;
        }
        .edit-btn:hover {
            background-color: #e0a800;
        }
        .delete-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 2px;
        }
        .delete-btn:hover {
            background-color: #c82333;
        }
        .add-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        .add-btn:hover {
            background-color: #218838;
        }
        .settings-btn {
            background-color: #6c757d;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        .settings-btn:hover {
            background-color: #5a6268;
        }
        .last-check {
            font-size: 0.9em;
            color: #666;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgb(0,0,0);
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .form-actions {
            text-align: right;
        }
        .action-buttons {
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Web服务监控系统</h1>
        
        <!-- 监控总览 -->
        <div class="overview">
            <div class="overview-item">
                <div class="overview-number normal-count" id="normalCount">0</div>
                <div class="overview-label">正常服务</div>
            </div>
            <div class="overview-item">
                <div class="overview-number error-count" id="errorCount">0</div>
                <div class="overview-label">异常服务</div>
            </div>
            <div class="overview-item">
                <div class="overview-number" id="totalCount">0</div>
                <div class="overview-label">总服务数</div>
            </div>
        </div>
        
        <div class="controls">
            <div>
                <button class="add-btn" onclick="openAddServiceModal()">添加服务</button>
                <button class="settings-btn" onclick="openSettingsModal()">设置</button>
            </div>
            <div>
                <button class="refresh-btn" onclick="checkAllServices()">刷新</button>
            </div>
        </div>
        
        <!-- 筛选条件 -->
        <div class="filters">
            <input type="text" class="filter-input" id="addressFilter" placeholder="按服务地址筛选">
            <select class="filter-select" id="statusFilter">
                <option value="">全部状态</option>
                <option value="正常">正常</option>
                <option value="异常">异常</option>
                <option value="未知">未知</option>
            </select>
            <button class="filter-btn" onclick="applyFilters()">查询</button>
            <button class="refresh-btn" onclick="clearFilters()">重置</button>
        </div>
        
        <table id="services-table">
            <thead>
                <tr>
                    <th>项目名</th>
                    <th>负责人</th>
                    <th>服务地址</th>
                    <th>运行状态</th>
                    <th>备注</th>
                    <th>状态日志</th>
                    <th>最后检查时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="services-body">
                <!-- 数据将通过JavaScript动态加载 -->
            </tbody>
        </table>
    </div>

    <!-- 添加服务的模态框 -->
    <div id="addServiceModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddServiceModal()">&times;</span>
            <h2>添加新服务</h2>
            <form id="addServiceForm">
                <div class="form-group">
                    <label for="serviceName">项目名:</label>
                    <input type="text" id="serviceName" required>
                </div>
                <div class="form-group">
                    <label for="serviceOwner">负责人:</label>
                    <input type="text" id="serviceOwner">
                </div>
                <div class="form-group">
                    <label for="serviceAddress">服务地址:</label>
                    <input type="text" id="serviceAddress" placeholder="例如: 192.168.1.1:8080" required>
                </div>
                <div class="form-group">
                    <label for="serviceRemark">备注:</label>
                    <input type="text" id="serviceRemark">
                </div>
                <div class="form-actions">
                    <button type="button" class="refresh-btn" onclick="closeAddServiceModal()">取消</button>
                    <button type="submit" class="add-btn">添加</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑服务的模态框 -->
    <div id="editServiceModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditServiceModal()">&times;</span>
            <h2>编辑服务</h2>
            <form id="editServiceForm">
                <input type="hidden" id="editServiceId">
                <div class="form-group">
                    <label for="editServiceName">项目名:</label>
                    <input type="text" id="editServiceName" required>
                </div>
                <div class="form-group">
                    <label for="editServiceOwner">负责人:</label>
                    <input type="text" id="editServiceOwner">
                </div>
                <div class="form-group">
                    <label for="editServiceAddress">服务地址:</label>
                    <input type="text" id="editServiceAddress" placeholder="例如: 192.168.1.1:8080" required>
                </div>
                <div class="form-group">
                    <label for="editServiceRemark">备注:</label>
                    <input type="text" id="editServiceRemark">
                </div>
                <div class="form-actions">
                    <button type="button" class="refresh-btn" onclick="closeEditServiceModal()">取消</button>
                    <button type="submit" class="edit-btn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 设置模态框 -->
    <div id="settingsModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeSettingsModal()">&times;</span>
            <h2>系统设置</h2>
            <div class="form-group">
                <label for="refreshInterval">自动刷新间隔(秒):</label>
                <input type="number" id="refreshInterval" min="10" max="300" value="30">
            </div>
            <div class="form-actions">
                <button type="button" class="refresh-btn" onclick="closeSettingsModal()">取消</button>
                <button type="button" class="edit-btn" onclick="saveSettings()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let refreshInterval = 30000; // 默认30秒
        let refreshIntervalId;
        let allServices = []; // 存储所有服务数据
        
        // 获取服务数据并更新表格
        function loadServices() {
            fetch('/api/services')
                .then(response => response.json())
                .then(services => {
                    allServices = services; // 保存所有服务数据
                    updateOverview(services); // 更新总览
                    renderServices(services); // 渲染服务表格
                })
                .catch(error => {
                    console.error('获取服务数据失败:', error);
                });
        }
        
        // 更新监控总览
        function updateOverview(services) {
            const normalCount = services.filter(service => service.status === '正常').length;
            const errorCount = services.filter(service => service.status === '异常').length;
            const totalCount = services.length;
            
            document.getElementById('normalCount').textContent = normalCount;
            document.getElementById('errorCount').textContent = errorCount;
            document.getElementById('totalCount').textContent = totalCount;
        }
        
        // 渲染服务表格
        function renderServices(services) {
            const tbody = document.getElementById('services-body');
            tbody.innerHTML = '';
            
            services.forEach(service => {
                const row = document.createElement('tr');
                
                // 根据状态设置样式
                let statusClass = 'unknown';
                let statusText = service.status;
                
                if (service.status === '正常') {
                    statusClass = 'normal';
                } else if (service.status === '异常') {
                    statusClass = 'error';
                }
                
                row.innerHTML = `
                    <td>${service.name}</td>
                    <td>${service.owner || ''}</td>
                    <td>${service.address}</td>
                    <td><span class="status ${statusClass}">${statusText}</span></td>
                    <td>${service.remark}</td>
                    <td>${service.status_log}</td>
                    <td class="last-check">${service.last_check}</td>
                    <td class="action-buttons">
                        <button class="refresh-btn" onclick="checkService(${service.id})">检查</button>
                        <button class="edit-btn" onclick="openEditServiceModal(${service.id})">编辑</button>
                        <button class="delete-btn" onclick="deleteService(${service.id})">删除</button>
                    </td>
                `;
                
                tbody.appendChild(row);
            });
        }
        
        // 应用筛选条件
        function applyFilters() {
            const addressFilter = document.getElementById('addressFilter').value.toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;
            
            let filteredServices = allServices;
            
            if (addressFilter) {
                filteredServices = filteredServices.filter(service => 
                    service.address.toLowerCase().includes(addressFilter)
                );
            }
            
            if (statusFilter) {
                filteredServices = filteredServices.filter(service => 
                    service.status === statusFilter
                );
            }
            
            updateOverview(filteredServices);
            renderServices(filteredServices);
        }
        
        // 清除筛选条件
        function clearFilters() {
            document.getElementById('addressFilter').value = '';
            document.getElementById('statusFilter').value = '';
            loadServices();
        }
        
        // 手动检查特定服务
        function checkService(serviceId) {
            fetch(`/api/check/${serviceId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.status) {
                        loadServices(); // 重新加载数据
                    }
                })
                .catch(error => {
                    console.error('检查服务失败:', error);
                });
        }
        
        // 批量检查所有服务
        function checkAllServices() {
            fetch('/api/check-all')
                .then(response => response.json())
                .then(data => {
                    if (data.status) {
                        loadServices(); // 重新加载数据
                    }
                })
                .catch(error => {
                    console.error('检查所有服务失败:', error);
                });
        }
        
        // 打开添加服务模态框
        function openAddServiceModal() {
            document.getElementById('addServiceModal').style.display = 'block';
        }
        
        // 关闭添加服务模态框
        function closeAddServiceModal() {
            document.getElementById('addServiceModal').style.display = 'none';
        }
        
        // 打开编辑服务模态框
        function openEditServiceModal(serviceId) {
            // 获取服务数据并填充到表单中
            fetch('/api/services')
                .then(response => response.json())
                .then(services => {
                    const service = services.find(s => s.id === serviceId);
                    if (service) {
                        document.getElementById('editServiceId').value = service.id;
                        document.getElementById('editServiceName').value = service.name;
                        document.getElementById('editServiceAddress').value = service.address;
                        document.getElementById('editServiceRemark').value = service.remark;
                        document.getElementById('editServiceOwner').value = service.owner || '';
                        document.getElementById('editServiceModal').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('获取服务数据失败:', error);
                });
        }
        
        // 关闭编辑服务模态框
        function closeEditServiceModal() {
            document.getElementById('editServiceModal').style.display = 'none';
        }
        
        // 打开设置模态框
        function openSettingsModal() {
            // 设置当前刷新间隔值
            document.getElementById('refreshInterval').value = refreshInterval / 1000;
            document.getElementById('settingsModal').style.display = 'block';
        }
        
        // 关闭设置模态框
        function closeSettingsModal() {
            document.getElementById('settingsModal').style.display = 'none';
        }
        
        // 保存设置
        function saveSettings() {
            const newInterval = parseInt(document.getElementById('refreshInterval').value) * 1000;
            if (newInterval >= 10000 && newInterval <= 300000) { // 限制在10秒到5分钟之间
                refreshInterval = newInterval;
                
                // 清除旧的定时器并设置新的定时器
                clearInterval(refreshIntervalId);
                refreshIntervalId = setInterval(loadServices, refreshInterval);
                
                closeSettingsModal();
            } else {
                alert('刷新间隔必须在10秒到300秒之间');
            }
        }
        
        // 添加新服务
        function addService(serviceData) {
            fetch('/api/services', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(serviceData)
            })
            .then(response => response.json())
            .then(data => {
                closeAddServiceModal();
                document.getElementById('addServiceForm').reset();
                loadServices(); // 重新加载数据
            })
            .catch(error => {
                console.error('添加服务失败:', error);
            });
        }
        
        // 更新服务
        function updateService(serviceId, serviceData) {
            fetch(`/api/services/${serviceId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(serviceData)
            })
            .then(response => response.json())
            .then(data => {
                closeEditServiceModal();
                loadServices(); // 重新加载数据
            })
            .catch(error => {
                console.error('更新服务失败:', error);
            });
        }
        
        // 删除服务
        function deleteService(serviceId) {
            if (confirm('确定要删除这个服务吗？')) {
                fetch(`/api/services/${serviceId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    loadServices(); // 重新加载数据
                })
                .catch(error => {
                    console.error('删除服务失败:', error);
                });
            }
        }
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadServices();
            // 每30秒自动刷新一次数据
            refreshIntervalId = setInterval(loadServices, refreshInterval);
            
            // 处理添加服务表单提交
            document.getElementById('addServiceForm').addEventListener('submit', function(e) {
                e.preventDefault();
                const serviceData = {
                    name: document.getElementById('serviceName').value,
                    address: document.getElementById('serviceAddress').value,
                    remark: document.getElementById('serviceRemark').value,
                    owner: document.getElementById('serviceOwner').value,
                };
                addService(serviceData);
            });
            
            // 处理编辑服务表单提交
            document.getElementById('editServiceForm').addEventListener('submit', function(e) {
                e.preventDefault();
                const serviceId = parseInt(document.getElementById('editServiceId').value);
                const serviceData = {
                    name: document.getElementById('editServiceName').value,
                    address: document.getElementById('editServiceAddress').value,
                    remark: document.getElementById('editServiceRemark').value,
                    owner: document.getElementById('editServiceOwner').value,
                };
                updateService(serviceId, serviceData);
            });
        });
    </script>
</body>
</html>